#include "elk_download_view.h"
#include "ui_elk_download_view.h"
#include "elk_download_item.h"
#include <QFileDialog>
#include <QStandardPaths>

ElkDownloadView::ElkDownloadView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ElkDownloadView),
    downloadManager_(new ElkDownloadManager(this))
{
    ui->setupUi(this);
}

ElkDownloadView::~ElkDownloadView()
{
    delete ui;
}

void ElkDownloadView::bind(QWeakPointer<ElkWebDelegate> delegate)
{
    if (!delegate_) {
        delegate_ = delegate;

        connect(delegate_.data(), SIGNAL(downloadRequested(const QString &,
                                                           const QString &)),
                this, SLOT(onDownloadRequested(const QString &,
                                               const QString &)));
    }
}

void ElkDownloadView::request(const QString &url, const QString &fileName)
{
    QString folder = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
    QString filePathName = folder + QString("/") + fileName;
    if (fileName.isEmpty()) {
        filePathName += QUrl(url).fileName();
    }

    filePathName = QFileDialog::getSaveFileName(this->window(), QString(),
                                                filePathName, QString(), nullptr);
    if (filePathName.isEmpty()) {
        return;
    }
    qDebug() << filePathName;

    auto task = downloadManager_->createDownloadTask(url, filePathName);
    if (task) {
        auto widget = new ElkDownloadItem(ui->scrollAreaWidgetContents);
        widget->attach(task);
        ui->verticalLayout->insertWidget(0, widget);
    }
}

void ElkDownloadView::onDownloadRequested(const QString &url, const QString &fileName)
{
    request(url, fileName);
}

void ElkDownloadView::on_lineEditURL_returnPressed()
{
    QString input = ui->lineEditURL->text();
    if (input.isEmpty()) {
        return;
    }

    QUrl url = QUrl::fromUserInput(input);
    request(url.toString(), url.fileName());
}

void ElkDownloadView::on_pushButtonDownload_clicked()
{
    on_lineEditURL_returnPressed();
}
